package guest

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	nhttp "net/http"
	"time"
	"wzgames/internal/api/bindo"
	"wzgames/internal/client"
	"wzgames/internal/gvalidator"
	"wzgames/internal/model/login"
	"wzgames/internal/response"
	"wzgames/pkg/logger"
	"wzgames/pkg/server/http"
	"wzgames/pkg/server/http/types"
)

func RegisterRoute(pGroup *gin.RouterGroup) {
	bizGroup := pGroup.Group("tour")
	http.MethodMapper(bizGroup, types.POST)(guestAuth())
}

var guestAuth = func() (string, func(c *gin.Context)) {
	uri := fmt.Sprintf("/sample")
	return uri, func(c *gin.Context) {
		resp := types.Response{}
		var params bindo.GuestBind
		if err := c.ShouldBind(&params); err != nil {
			resp.Code = response.ErrBadRequest
			c.JSON(nhttp.StatusOK, resp)
			return
		}
		if len(params.AgtCode) > 15 || !gvalidator.IsAlphaNumeric(params.AgtCode) {
			resp.Code = response.ErrBadRequest
		} else if !gvalidator.IsAlphaNumeric(params.Currency) || len(params.Currency) > 10 {
			resp.Code = response.ErrBadRequest
		} else if !gvalidator.IsAlphaNumeric(params.Lang) || len(params.Lang) > 20 {
			resp.Code = response.ErrBadRequest
		}
		if resp.Code != 0 {
			c.JSON(nhttp.StatusOK, resp)
			return
		}

		agtId, err := gvalidator.DecodeAgentID(params.AgtCode)
		if err != nil {
			logger.Error("[API] guest auth fail on decode agent code", zap.String("AgtCode", params.AgtCode))
			resp.Code = response.ErrBadRequest
			c.JSON(nhttp.StatusOK, resp)
			return
		}

		req := &login.GuestReq{
			AgtID:    agtId,
			AgtCode:  params.AgtCode,
			Currency: params.Currency,
			Lang:     params.Lang,
			ClientIP: c.ClientIP(),
		}

		reply := &login.GuestReply{}
		rpcctx, cancelFn := context.WithTimeout(context.Background(), 5*time.Second)
		err = client.GetCatClient().Call(rpcctx, "GuestGen", req, reply)
		cancelFn()
		if err != nil {
			resp.Code = response.ErrInternal
			logger.Error("[API] guest auth gen fail", zap.Error(err))
		} else {
			resp.Code = int16(reply.Code)
			if reply.Code == 0 {
				resp.Code = 200
				resp.Data = reply
			}
		}

		c.JSON(nhttp.StatusOK, resp)
		return
	}
}
